#include "usart.h"
#include "string.h"
#include "buffer.h"
#include "timer.h"

extern uint8_t* data;
uint32_t  num = 0;
void UART_IntReceive(LPC_UART_TypeDef * UART_PORT);
UART_BUF_R uart0RxBuf;

void uart_init(void)
{
  UART_CFG_Type UARTConfigStruct;
	PINSEL_CFG_Type PinCfg;
  UART_FIFO_CFG_Type UARTFIFOConfigStruct;

	PinCfg.Funcnum = 1;
	PinCfg.OpenDrain = 0;
	PinCfg.Pinmode = 0;
	PinCfg.Pinnum = 2;				//TX
	PinCfg.Portnum = 0;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 3;				//RX
	PINSEL_ConfigPin(&PinCfg);
	
	UART_ConfigStructInit(&UARTConfigStruct);
	UARTConfigStruct.Baud_rate = 115200;
	UART_Init(LPC_UART0,&UARTConfigStruct);
	
  UARTFIFOConfigStruct.FIFO_Level = UART_FIFO_TRGLEV3;	/**< ??? 14???    */
	
	UARTFIFOConfigStruct.FIFO_DMAMode = DISABLE;
	UARTFIFOConfigStruct.FIFO_ResetRxBuf = ENABLE;
	UARTFIFOConfigStruct.FIFO_ResetTxBuf = ENABLE;
	
	UART_FIFOConfig((LPC_UART_TypeDef *)LPC_UART0, &UARTFIFOConfigStruct);
	
	UART_TxCmd(LPC_UART0, ENABLE);
	
	UART_IntConfig((LPC_UART_TypeDef *)LPC_UART0, UART_INTCFG_RBR, ENABLE);	
	
	NVIC_SetPriority(UART0_IRQn, (0x01<<2 | 0x01));
	
	NVIC_EnableIRQ(UART0_IRQn);
}

void UART0_IRQHandler(void)
{
  uint32_t intsrc, tmp;

  intsrc = UART_GetIntId(LPC_UART0);
  tmp = intsrc & UART_IIR_INTID_MASK;
	
	if(tmp == UART_IIR_INTID_CTI){
    Time0Cmd(DISABLE);
    
		UART_IntReceive(LPC_UART0);
    
//    UART_SendByte(LPC_UART0, 0x16);
//    while (UART_CheckBusy(LPC_UART0) == SET);
    
    addBuffer(&uart0RxBuf);
		memset(&uart0RxBuf,0,sizeof(UART_BUF_R));
	}

	if(tmp == UART_IIR_INTID_RDA)
	{
    Time0Cmd(DISABLE);//复位定时器
		UART_IntReceive(LPC_UART0);
    Time0Cmd(ENABLE); //启动定时器空闲判断
	}
		
}


void UART_IntReceive(LPC_UART_TypeDef * UART_PORT)
{
	uint8_t tmpc;
	uint32_t rLen=0;
	
	while(1){
		rLen = UART_Receive(UART_PORT, &tmpc, 1, NONE_BLOCKING);
		if(rLen){
			if(UART_PORT == LPC_UART0){
				if(uart0RxBuf.length < BUFFER_LENGTH){
					uart0RxBuf.rx[uart0RxBuf.length] = tmpc;
					uart0RxBuf.length++;
				}
			}
		}
		else{
			break;
		}
	}
}

void Uart0Send(uint8_t *p, uint32_t length)
{
  uint32_t i = 0;
  for(i = 0; i < length; i++)
  {
//    UART_SendByte(LPC_UART0, length>>8);
//    while (UART_CheckBusy(LPC_UART0) == SET);
//    UART_SendByte(LPC_UART0, length&0xff);
//    while (UART_CheckBusy(LPC_UART0) == SET);
    
    UART_SendByte(LPC_UART0, *(p+i));
    while (UART_CheckBusy(LPC_UART0) == SET);
  }
}

void UartAddBuffer()
{
  addBuffer(&uart0RxBuf);
  memset(&uart0RxBuf,0,sizeof(UART_BUF_R));
}








